//
//  WBStatuseInfoViewModel.m
//  sinaWeibo
//
//  Created by 李江波 on 2016/11/17.
//  Copyright © 2016年 lijiangbo. All rights reserved.
//

#import "WBStatuseInfoViewModel.h"
#import "WBStatusesModel.h"
#import "WBEmoticon.h"
#import "WBEmoticonManager.h"
#import <YYText.h>

@implementation WBStatuseInfoViewModel


-(void)setStatuse:(WBStatusesModel *)statuse{

    _statuse = statuse;
    if (statuse.retweeted_status == nil) {
        
        self.imgURLs = statuse.pic_urls;
        
    }else{
    
        self.imgURLs = statuse.retweeted_status.pic_urls;
    }
    
    
    
}

-(NSMutableAttributedString *)originalText{

 
    return [self dealWeiboText:self.statuse.text];
}

-(NSMutableAttributedString *)retweetedText{


    return [self dealWeiboText:self.statuse.retweeted_status.text];
}

#pragma mark : - 将微博正文/转发微博正文处理成富文本
-(NSMutableAttributedString *)dealWeiboText:(NSString *)str {
//转发微博可能为空
    if (str == nil) {
        return nil;
    }
    
    //1.实例化正则表达式对象
//    NSString *pattern = @"\\[.*?\\]";
//    
//    NSRegularExpression *regex = [[NSRegularExpression alloc]initWithPattern:pattern options:0 error:nil];
    
    NSArray<NSTextCheckingResult *> *result = [emojiRegex matchesInString:str options:0 range:NSMakeRange(0, str.length)];

    //3.遍历结果集  获取表情字符串  ->> 倒序遍历
    NSMutableAttributedString *strM = [[NSMutableAttributedString alloc]initWithString:str];
    UIFont *font = [UIFont systemFontOfSize:18];
    CGFloat lineHeight = font.lineHeight;
    
//    if (result.count == 0) {
//        NSLog(@"%@",strM);
//        return strM;
//    }
    
    [[[result reverseObjectEnumerator] allObjects] enumerateObjectsUsingBlock:^(NSTextCheckingResult * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
       
        NSRange range = [obj rangeAtIndex:0];
        NSString *subStr = [str substringWithRange:range];
        
        
        WBEmoticon *em = [[WBEmoticonManager shared] findEmoticonByImageName:subStr];
//        NSLog(@"%@",em);
        //查找到表情模型就开始后续的操作
        /*
         // 嵌入 UIImage
         UIImage *image = [UIImage imageNamed:@"dribbble64_imageio"];
         attachment = [NSMutableAttributedString yy_attachmentStringWithContent:image contentMode:UIViewContentModeCenter attachmentSize:image.size alignToFont:font alignment:YYTextVerticalAlignmentCenter];
         
         */
        if (em != nil) {
            
            UIImage *img = [UIImage imageNamed:em.imagePath inBundle:[WBEmoticonManager shared].emoticonBundle compatibleWithTraitCollection:nil];
            
            NSMutableAttributedString *attachment = [NSMutableAttributedString yy_attachmentStringWithContent:img contentMode:UIViewContentModeScaleAspectFit attachmentSize:CGSizeMake(lineHeight, lineHeight) alignToFont:font alignment:YYTextVerticalAlignmentCenter];
            //将图片富文本替换到str对应的可变的富文本中
            [strM replaceCharactersInRange:range withAttributedString:attachment];
        }
        
    }];
    //改变文本字体大小
    [strM addAttributes:@{NSFontAttributeName : [UIFont systemFontOfSize:18]} range:NSMakeRange(0, strM.length)];
//    NSLog(@"%@",strM);
    
    [self addHighlighted:atRegex strM:strM];
    [self addHighlighted:themeRegex strM:strM];
    [self addHighlighted:urlRegex strM:strM];
    
    return strM;
}
#pragma mark : - 将微博正文/转发微博正文关键字高亮

-(void)addHighlighted:(NSRegularExpression *)regex strM:(NSMutableAttributedString *)strM {

//    NSRegularExpression *regex = [[NSRegularExpression alloc]initWithPattern:pattern options:0 error:nil];
    
    NSArray<NSTextCheckingResult *> *results = [regex matchesInString:strM.string options:0 range:NSMakeRange(0, strM.length)];
    
    for (NSTextCheckingResult *result in results) {
        
        NSRange range = [result rangeAtIndex:0];
        
        [strM addAttributes:@{NSForegroundColorAttributeName : [UIColor orangeColor]} range:range];
        /*
         // 1. 创建一个"高亮"属性，当用户点击了高亮区域的文本时，"高亮"属性会替换掉原本的属性
         YYTextBorder *border = [YYTextBorder borderWithFillColor:[UIColor grayColor] cornerRadius:3];
         
         YYTextHighlight *highlight = [YYTextHighlight new];
         [highlight setColor:[UIColor whiteColor]];
         [highlight setBackgroundBorder:highlightBorder];
         highlight.tapAction = ^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect) {
         NSLog(@"tap text range:...");
         // 你也可以把事件回调放到 YYLabel 和 YYTextView 来处理。
         };
         
         // 2. 把"高亮"属性设置到某个文本范围
         [attributedText yy_setTextHighlight:highlight range:highlightRange];
         */
        YYTextBorder *border = [YYTextBorder borderWithFillColor:[UIColor grayColor] cornerRadius:3];
        YYTextHighlight *highlight = [YYTextHighlight new];
        [highlight setColor:[UIColor whiteColor]];
        [highlight setBackgroundBorder:border];
        
        [strM yy_setTextHighlight:highlight range:range];
    }
    
   
}


-(NSURL *)url{

    return  [NSURL URLWithString:self.statuse.user.avatar_large];
}

-(UIImage *)mbrankImg{
 // 会员等级 1 ~ 6
    NSInteger num = self.statuse.user.mbrank;
    
    UIImage *img;
    if (num > 0 && num < 7) {
        
        NSString *imgStr = [NSString stringWithFormat:@"common_icon_membership_level%zd",num];
        img = [UIImage imageNamed:imgStr];
    }else{
    
        img = [UIImage imageNamed:@"common_icon_membership_expired"];
    }
    return img;
}

-(UIImage *)verified_typeImg{
 /// 认证类型: -1：没有认证，0：认证用户，2,3,5: 企业认证，220: 达人
    UIImage *img;
    switch (self.statuse.user.verified_type) {
        case 0:
            img = [UIImage imageNamed:@"avatar_vip"];
            break;
        case 2:
        case 3:
        case 5:
            img = [UIImage imageNamed:@"avatar_enterprise_vip"];
            break;
        case 220:
            img = [UIImage imageNamed:@"avatar_grassroot"];
            break;
            
        default:
            img = [UIImage imageNamed:@""];
            break;
    }
    return img;
}

///重新设置时间
-(NSString *)sendTime{
//"Sat Nov 19 20:30:03 +0800 2016"
//    NSString *str = @"Sat Nov 19 20:30:03 +0800 2015";
    
    NSDateFormatter *dateFormatter = formatter;
    dateFormatter.dateFormat = @"EEE MMM dd HH:mm:ss Z yyyy";
    //在真机上必须设置本地化信息否则转换失败
    dateFormatter.locale = [[NSLocale alloc]initWithLocaleIdentifier:@"en"];
    
    NSDate *sinceDate = [dateFormatter dateFromString:self.statuse.created_at];
    NSDate *currentDate = [NSDate date];
    
    NSCalendar *calender = [NSCalendar currentCalendar];
    NSDateComponents *result = [calender components:NSCalendarUnitDay|NSCalendarUnitYear fromDate:sinceDate toDate:currentDate options:0];
    
    if (result.year == 0) {
        //今年
        if ([calender isDateInToday:sinceDate]) {
            //今天
            NSInteger second = [currentDate timeIntervalSinceDate:sinceDate];
            if (second < 60) {
                //刚刚
                return @"刚刚";
            }else if (second < 3600){
                //##分钟前
                return [NSString stringWithFormat:@"%zd分钟前",second / 60];
            }else{
                //##小时前
                return [NSString stringWithFormat:@"%zd小时前",second / 3600];
            }
        }else if ([calender isDateInYesterday:sinceDate]){
            //昨天 HH:mm
            dateFormatter.dateFormat = @"HH:mm";
            return [NSString stringWithFormat:@"昨天 %@",[dateFormatter stringFromDate:sinceDate]];
        }else{
            //其他 MM-dd HH:mm
            dateFormatter.dateFormat = @"MM-dd HH:mm";
            
            return [dateFormatter stringFromDate:sinceDate];
        }
        
    }else{
        //其他年
        dateFormatter.dateFormat = @"yyyy-MM-dd";
        return [dateFormatter stringFromDate:sinceDate];
    }

}
///微博来源
-(NSString *)weiboSource{
    //"<a href=\"http://app.weibo.com/t/feed/6vtZb0\" rel=\"nofollow\">微博 weibo.com</a>"
    NSString *source = self.statuse.source;
    
    NSString *startFlag = @"\">";
    NSString *endFlag = @"</a>";
    NSRange startRange = [source rangeOfString:startFlag];
    NSRange endRange = [source rangeOfString:endFlag];
    NSRange range = NSMakeRange(startRange.location + startRange.length, endRange.location - (startRange.location + startRange.length));
    
    if (range.location > 1000) {
        
        return @"未知来源";
    }
    NSString *newSource = [source substringWithRange:range];
    
    return  newSource;
}




@end
